package com.demo.support.Interceptor.jwebinterhandle;

import java.util.Arrays;
import java.util.List;

import org.quartz.CronExpression;

import com.alibaba.fastjson.JSON;
import com.demo.support.task.DynamicJob;
import com.jweb.plugin.jdbc.JdbcTemplate;
import com.jweb.plugin.quartz.QuartzPlugin;
import com.jweb.plugin.quartz.dto.CronTriggerDto;
import com.jweb.plugin.quartz.dto.JobDetailDto;
import com.jweb.plugin.quartz.dto.SchedulerDto;
import com.jweb.util.FormatUtil;

public class DynamicQuartz {
	public static List<JobBean> listjob;

	/**
	 * 最小10s
	 */
	private long millis = 1000 * 10;

	/**
	 * 
	 CREATE TABLE `sys_job` ( `id` int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
	 * `job_name` varchar(255) NOT NULL, `cron` varchar(20) NOT NULL, `state`
	 * tinyint(1) NOT NULL COMMENT '1启动 0禁用 2异常', `post_url` varchar(500)
	 * DEFAULT '', `remark` varchar(255) DEFAULT '', PRIMARY KEY (`id`) )
	 * 
	 * @author Yuanqy
	 *
	 */
	public static class JobBean {
		public int id;
		public String job_name;
		public String cron;
		public int state;
		public String remark;
		public String post_url;
	}

	public DynamicQuartz(long sleepTime) {
		this.millis = sleepTime > millis ? sleepTime : millis;
	}

	public void start() {
		try {
			boolean bo = true;
			QuartzPlugin qp = new QuartzPlugin();
			JdbcTemplate jt = new JdbcTemplate("jdbc:mysql://localhost:3306", "root", "root");
			while (bo) {
				qp.start();
				System.err.println(">>>\t读取配置");
				jt.openTransaction();
				listjob = jt.queryListBean("select * from pay.sys_job", null, JobBean.class);
				for (JobBean jb : listjob) {
					if (jb.state == 1) {
						if (CronExpression.isValidExpression(jb.cron)) {
							String jobName = "jd" + jb.id;
							String triggerName = "tg" + jb.id;
							String cron = jb.cron;
							String jobGroup = jb.job_name;
							String triggerGroup = jb.job_name;
							SchedulerDto dto = new SchedulerDto(new CronTriggerDto(triggerName, triggerGroup, cron), new JobDetailDto(jobName, jobGroup, DynamicJob.class));
							qp.addJob(dto);
						} else {
							System.err.println(">>>\t定时器格式错误：" + JSON.toJSONString(jb));
							jt.update("update pay.sys_job set state=2,remark=? where id=?", new Object[] { FormatUtil.getNowTime() + "格式错误,请检查!", jb.id });
						}
					}
				}
				jt.commit();
				Thread.sleep(millis);
				qp.stop();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
